﻿function dateParse(value) {
    try { 
        var a;
        if(typeof value==="string") {
            if (value.indexOf("Date") >=0 ) {
                a=/^\/Date\(([0-9]+)\)\/$/.exec(value);
                if (a) {
                    return new Date(parseInt(a[1],10));
                }
            }
        }
        return value;
    }
    catch(e) {return null;}
}
    
function buildPostList(data) {
    var text='<ul>';
    $.each(data, function(index, optionData) {
        var created = dateParse( optionData.Created  )
        text = text + "<li>" + '<div class="title"><a href="' + optionData.Url +'">' + optionData.Title + "</a> " 
        
        + '<div class="dateposted">' + created.toLocaleString() + "</div>"
        + "</div>" + '<div class="body">' + optionData.Body.substring(0,300) +  "</div>" +
        '<div class="edit"><a href="' + optionData.EditUrl + '">Edit</a>' +
        '<a class="delete" href="' + optionData.DeleteUrl + '">Delete</a></div>' +
        '<div class="clear"/>' +
          "</li>";
    });

    text = text + "</ul>";
    $('#posts').html(
        text
    );
    
    addDeleteEvent();        
}

function addDeleteEvent() {
    $("a.delete").click(function(event) {
        var deleteUrl = this.href;
        var monthFilter = $("#monthList option:selected").val();  
        $.getJSON(deleteUrl, null, function(data) {});
        //alert(monthFilter);
        $.getJSON("/Json/Posts/" + monthFilter, null, function(postList) {
            buildPostList(postList);
        });
        //alert(this.href);
        
        return false;
    });
}


$.fn.clearSelect = function() {
    return this.each(function() {
        if (this.tagName == 'SELECT')
            this.options.length = 0;
    });
 } 
 
$.fn.fillSelect = function(data) {
    return this.clearSelect().each(function() {
        if (this.tagName == 'SELECT') {
            var dropdownList = this;
            $.each(data, function(index, optionData) {
                var option = new Option(optionData.Text, optionData.Value);
                
                if ($.browser.msie) {
                    dropdownList.add(option);
                }
                else {
                    dropdownList.add(option, null);
                }
            });
        }
    });
 }